import logging
import platform
from typing import List
import os
from notify.base import NotificationSender

logger = logging.getLogger(__name__)

class AudioSender(NotificationSender):
    """
    音频播放通知实现类
    """

    def __init__(self):
        self.system = platform.system()
        self._initialize_audio()

    def _initialize_audio(self):
        """
        根据操作系统初始化音频播放器
        """
        try:
            if self.system == "Windows":
                import winsound
                self.winsound = winsound
            elif self.system == "Darwin":  # macOS
                import subprocess
                self.subprocess = subprocess
            elif self.system == "Linux":
                import subprocess
                self.subprocess = subprocess
            else:
                logger.warning(f"Unsupported operating system for audio notification: {self.system}")
        except ImportError as e:
            logger.error(f"Failed to import required modules for audio notification: {e}")

    def connect(self) -> bool:
        """
        音频播放不需要连接服务

        :return: 总是返回True
        """
        logger.info("Audio sender does not require connection")
        return True

    def disconnect(self) -> None:
        """
        音频播放不需要断开连接
        """
        logger.info("Audio sender does not require disconnection")

    def send(self, subject: str, content: str, recipients: List[str], **kwargs) -> bool:
        """
        播放音频通知

        :param subject: 通知主题（用于日志记录）
        :param content: 通知内容（可作为音频文件路径）
        :param recipients: 接收者列表（不使用）
        :param kwargs: 其他参数，支持duration（播放时长）、frequency（频率）和sound_file（音频文件路径）
        :return: 播放是否成功
        """
        try:
            # 检查是否提供了音频文件路径
            sound_file = kwargs.get('sound_file')
            
            if sound_file and os.path.exists(sound_file):
                # 如果提供了有效的音频文件路径，则播放该文件
                return self._play_sound_file(sound_file)
            else:
                # 否则播放默认的蜂鸣声
                duration = kwargs.get('duration', 1000)  # 默认播放时长1000毫秒
                frequency = kwargs.get('frequency', 800)  # 默认频率800Hz
                return self._play_beep_sound(duration, frequency)

        except Exception as e:
            logger.error(f"Failed to play audio notification: {e}")
            return False

    def _play_sound_file(self, sound_file: str) -> bool:
        """
        播放指定的音频文件

        :param sound_file: 音频文件路径
        :return: 播放是否成功
        """
        try:
            if self.system == "Windows":
                # 使用 SND_FILENAME | SND_NODEFAULT 标志确保播放指定的音频文件
                flags = self.winsound.SND_FILENAME | self.winsound.SND_NODEFAULT
                self.winsound.PlaySound(sound_file, flags)
            elif self.system == "Darwin":  # macOS
                self.subprocess.run(["afplay", sound_file])
            elif self.system == "Linux":
                # 尝试使用paplay播放音频文件
                self.subprocess.run(["paplay", sound_file], 
                                  check=False, stdout=self.subprocess.DEVNULL, stderr=self.subprocess.DEVNULL)
            else:
                logger.warning(f"Audio file playback not supported on {self.system}")
                return False
                
            logger.info(f"Audio file played successfully: {sound_file}")
            return True
        except Exception as e:
            logger.error(f"Failed to play audio file {sound_file}: {e}")
            return False

    def _play_beep_sound(self, duration: int, frequency: int) -> bool:
        """
        播放蜂鸣声

        :param duration: 持续时间（毫秒）
        :param frequency: 频率（赫兹）
        :return: 播放是否成功
        """
        try:
            if self.system == "Windows":
                # Windows系统使用winsound
                self.winsound.Beep(frequency, duration)
            elif self.system == "Darwin":  # macOS
                # macOS系统使用afplay播放系统声音
                self.subprocess.run(["afplay", "/System/Library/Sounds/Ping.aiff"])
            elif self.system == "Linux":
                # Linux系统使用speaker-test
                self.subprocess.run(["speaker-test", "-t", "sine", "-f", str(frequency), "-l", "1", "-s", "1"],
                                  check=False, stdout=self.subprocess.DEVNULL, stderr=self.subprocess.DEVNULL)
            else:
                logger.warning(f"Beep sound not supported on {self.system}")
                return False

            logger.info(f"Beep sound played successfully: {duration}ms, {frequency}Hz")
            return True
        except Exception as e:
            logger.error(f"Failed to play beep sound: {e}")
            return False


if __name__ == '__main__':
    from notify import AudioSender

    audio_sender = AudioSender()

    # 播放自定义音频文件
    audio_sender.send("重要通知", "您有一条新消息", [], sound_file=r"/static/audio/notify.wav")